﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using Maxleaf.EDI.API.Contract;
using Maxleaf.EDI.API.Contract.Client.Parameters;
using Maxleaf.EDI.API.Contract.Faults;
using Maxleaf.EDI.Core.Handlers;
using Maxleaf.EDI.Infrastructure.Logging;
using TinyIoC;

namespace Maxleaf.EDI.API
{
    public class ClientService : IClientService
    {
        #region Constants and Fields

        private readonly TinyIoCContainer container;

        private readonly ILogger logger;

        #endregion

        #region Constructors and Destructors

        public ClientService()
        {
            this.container = TinyIoCContainer.Current;
            this.logger = this.container.Resolve<ILogger>();
        }

        #endregion

        public AuthenticateResult Authenticate(AuthenticateParameters parameters)
        {
            try
            {
                var handler = this.container.Resolve<IQueryHandler<AuthenticateParameters,AuthenticateResult>>();

                return handler.Handle(parameters);
            }
            catch (Exception e)
            {
                this.logger.Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Message, e);
                throw new FaultException<GeneralFault>(new GeneralFault(e.Message), e.Message);
            }
        }


        public GetUserDBsResult GetUserDBs(GetUserDBsParameters parameters)
        {
            try
            {
                var handler = this.container.Resolve<IQueryHandler<GetUserDBsParameters, GetUserDBsResult>>();

                return handler.Handle(parameters);
            }
            catch (Exception e)
            {
                this.logger.Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Message, e);
                throw new FaultException<GeneralFault>(new GeneralFault(e.Message), e.Message);
            }
        }


        public void ResetPassword(Contract.Client.Commands.ResetPasswordCommand command)
        {
            try
            {
                var handler = this.container.Resolve<ICommandHandler<Maxleaf.EDI.API.Contract.Client.Commands.ResetPasswordCommand>>();

                handler.Handle(command);
            }
            catch (Exception e)
            {
                this.logger.Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Message, e);
                throw new FaultException<GeneralFault>(new GeneralFault(e.Message), e.Message);
            }
        }
    }
}
